<?php
namespace app\login\controller;

use think\Controller;

class Upload extends Controller 
{
	/**
	 * 上传base64图片
	 * @author 秋水
	 * @DateTime 2018-10-23T18:33:09+0800
	 */
	public function index()
	{
		// $param = $this->param;
		// $data = $param['base64'];
		$data = input('base64', '');
		if($data == '') {
			return json(['code'=>0,'msg'=>'图片信息错误','data'=>json_encode(input())]);
		}

		$url = $this->base64_image_content($data,'public/uploads',2);

		if($url) {
			return json(['code'=>1,'message'=>'上传成功','data'=>['domain'=>request()->domain(),'url'=>$url]]);
		} else {
			return json(['code'=>2,'message'=>'上传失败','data'=>['domain'=>request()->domain(),'url'=>$url]]);
		}
	}

	/**
	 * 获取文件类型
	 * @author 秋水
	 * @DateTime 2018-12-30T10:23:27+0800
	 */
	private function get_type($content)
	{
		$bin = substr($content,0,2);
		$strInfo = @unpack("C2chars", $bin);
		$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
		$fileType = '';
		switch ($typeCode)
		{
			case 7790:
				$fileType = 'exe';
				break;
			case 7784:
				$fileType = 'midi';
				break;
			case 8297:
				$fileType = 'rar';
				break;
			case 255216:
				$fileType = 'jpg';
				break;
			case 7173:
				$fileType = 'gif';
				break;
			case 6677:
				$fileType = 'bmp';
				break;
			case 13780:
				$fileType = 'png';
				break;
			default:
				// echo 'unknown';
				$fileType = '-';
		}
		return $fileType;
	}

	/**
	 * base64信息转存为文件
	 * @author 秋水
	 * @DateTime 2018-12-30T10:22:47+0800
	 */
	protected function base64_image_content($base64_image_content,$path,$index=0){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = $path."/".date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file.time().$index.".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return '/'.$new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}